<template>
  <div
    v-if="!initializing"
    class="vc-page vc-flex-column vc-grow-height"
    :style="visual.parseStyle(pageNode.currStyle)"
  >
    <vc-page-comp v-for="(child, index) in pageNode.children" :node="child" :key="index" />
  </div>
</template>

<script setup>
import { ref, onMounted, provide, nextTick } from 'vue';
import api from "@/http/api";
import visual from "@/visual/js/visual";

const props = defineProps({
  dataPageId: String,
  pageInfo: Object,
  visualJson: Object,
  operate: {
    type: String,
    default: '',
  },
  inputParam: {
    type: Object,
    default: () => {}
  }
});

const initializing = ref(true);
const pageInfo = ref({});
const pageNode = ref({});
const pageData = ref({});
provide('operate', props.operate);
provide('pageData', pageData);

const loadPageInfo = async () => {
  if (props.visualJson) {
    pageNode.value = props.visualJson;
  } else {
    if (props.pageInfo) {
      pageInfo.value = props.pageInfo;
    } else {
      const res = await api.post('/business/page/' + props.dataPageId());
      pageInfo.value = res.data || {};
    }

    if (pageInfo.value.compList
      && pageInfo.value.compList.length > 0
      && pageInfo.value.compList[0].id) {
      const res = await api.post('/business/page-comp/' + pageInfo.value.compList[0].id);
      pageNode.value = JSON.parse((res.data || {}).visualJson);
    }
  }

  if (!pageNode.value.currStyle
    && pageNode.value.styleList
    && pageNode.value.styleList.length > 0) {
    pageNode.value.currStyle = pageNode.value.styleList[0].style || {};
  }
};

const init = async () => {
  if (!props.dataPageId && !props.pageInfo && !props.visualJson) {
    return;
  }

  initializing.value = true;
  await loadPageInfo();
  await nextTick(() => initializing.value = false);
};

const getData = () => {
  return pageData.value;
};

onMounted(() => {
  init();
});

defineExpose({ getData });
</script>

<style scoped>
.vc-page {
  overflow: auto;
}
</style>